package eu.codlab.twitteirb;

import java.util.ArrayList;

import eu.codlab.twitteirb.manage.OnMessageReceiveListener;
import eu.codlab.twitteirb.preferences.ApplicationPreferences;
import android.os.Bundle;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;

public class TwittEirbActivity extends FragmentActivity implements OnSharedPreferenceChangeListener, OnMessageReceiveListener {
	private TweetsFragment _tweets_fragment;
	private LoginFragment _login_fragment;
	private PeersFragment _peers_fragment;

	public static String PREF="CODLABPREF";
	public static String FIELD="ERER";
	private SharedPreferences _shared;

	private void start(){
		if(_shared == null){
			_shared = this.getSharedPreferences(TwittEirbActivity.PREF, 0);
			_shared.registerOnSharedPreferenceChangeListener(this);
		}
		Intent i = new Intent(this, TwittEirbService.class);
		startService(i);

		if(TwittEirbService.getService() != null){
			TwittEirbService.getService().bindListener(this);
			//	TwittEirbService.getService().go();
		}
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_twitt_eirb);

		start();
	}

	@Override
	public void onPause(){
		if(_shared != null)
			_shared.unregisterOnSharedPreferenceChangeListener(this);
		_shared = null;
		//if(TwittEirbService.getService() != null)
		//	TwittEirbService.getService().unbindListener(this);
		super.onPause();
	}

	@Override
	public void onResume(){
		start();
		super.onResume();
		initFragments();

		if(!(TwittEirbService.getService() != null && TwittEirbService.getService().getStateConnection() == true))
			refresh();
		else if(TwittEirbService.getService().getStateConnection() == true)
			pushtweets();

	}

	public void initFragments(){
		if(_tweets_fragment != null || _peers_fragment != null)
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(_tweets_fragment != null && _tweets_fragment.isSmartphone());

	}

	private void pop(Fragment fragment){
		//Log.d("pop","pop");
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction xact = fm.beginTransaction();
		if(fragment == _peers_fragment)
			xact.setCustomAnimations(R.anim.slide100dptoleft, R.anim.slide100dptoleft);
		/*else
			xact.setCustomAnimations(R.anim.slidein, R.anim.slideout_totop,R.anim.slidein,R.anim.slideout);*/
		xact.remove(fragment);
		xact.commit();
		fm.popBackStack();
		//fm.popBackStackImmediate();
	}
	@Override
	public void onDestroy(){
		if(_shared != null)
			_shared.unregisterOnSharedPreferenceChangeListener(this);
		_shared = null;
		if(TwittEirbService.getService() != null)
			TwittEirbService.getService().unbindListener(this);
		super.onDestroy();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_twitt_eirb, menu);
		return true;
	}
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if(TwittEirbActivity.FIELD.equals(key) && TwittEirbService.getService() != null && TwittEirbService.getService().bindListener(this))
			refresh();
	}

	private void pushtweets(){
		if(_tweets_fragment == null){
			_tweets_fragment = new TweetsFragment();

			try{
				FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
				fragmentTransaction.replace(R.fragments.main, _tweets_fragment);
				fragmentTransaction.addToBackStack(null);
				fragmentTransaction.commit();
			}catch(Exception e){

			}
			initFragments();
		}else{
			_tweets_fragment.refresh();
		}
		TwittEirbService.getService().setRead();
		getSupportActionBar().setDisplayHomeAsUpEnabled(_tweets_fragment.isSmartphone());
	}

	@Override
	public void onNewMessage(ArrayList<Tweet> tweets) {
		runOnUiThread(new Runnable(){
			public void run(){
				pushtweets();
			}
		});
	}
	@Override
	public void onAvatarLoaded() {
		runOnUiThread(new Runnable(){
			public void run(){
				pushtweets();
			}
		});
	}

	private void refresh(){
		popTopFragment();
		if(_tweets_fragment != null){
			pop(_tweets_fragment);
			_tweets_fragment=null;
			getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		}


		if(_login_fragment == null){
			_login_fragment = new LoginFragment();

			try{
				FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
				fragmentTransaction.replace(R.fragments.main, _login_fragment);
				fragmentTransaction.commit();
			}catch(Exception e){

			}
		}
	}

	private boolean hasFragment(){
		return _tweets_fragment != null;
	}
	private boolean hasTopFragment(){
		return _peers_fragment != null;
	}
	private void popTopFragment(){
		if(_peers_fragment != null)
			pop(_peers_fragment);
		_peers_fragment=null;
	}
	private void pushTopFragment(){
		if(_tweets_fragment != null && _tweets_fragment.isSmartphone() && _peers_fragment ==null){
			_peers_fragment = new PeersFragment();
			try{
				FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.slidein_fromleft, R.anim.slide100dptoleft);
				fragmentTransaction.add(R.fragments.main, _peers_fragment);
				fragmentTransaction.addToBackStack(null);

				fragmentTransaction.commit();
			}catch(Exception e){

			}
		}

	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:
			if(!onBackCustom() && hasFragment() && _tweets_fragment != null && _tweets_fragment.isSmartphone())
				pushTopFragment();
			break;
		case R.id.menu_settings:
			Intent i = new Intent(this, ApplicationPreferences.class);
			startActivity(i);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onRequestLogin(){
		runOnUiThread(new Runnable(){
			public void run(){
				refresh();
			}
		});
	}
	public TweetsAdapter getTweetsAdapter() {
		return new TweetsAdapter(this);
	}
	public ListAdapter getPeersAdapter() {
		return new PeersAdapter(this);
	}

	public boolean onBackCustom(){
		if(hasTopFragment())
			popTopFragment();
		else
			return false;
		return true;
	}
	@Override
	public void onBackPressed(){
		if(!onBackCustom()){
			while(getSupportFragmentManager().getBackStackEntryCount()>0)
				getSupportFragmentManager().popBackStackImmediate();
			super.onBackPressed();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle save){
		super.onSaveInstanceState(save);
		if(_tweets_fragment != null)
			getSupportFragmentManager().putFragment(save, "TWEETS", _tweets_fragment);
		if(_login_fragment != null)
			getSupportFragmentManager().putFragment(save, "LOGIN", _login_fragment);
		if(_peers_fragment != null)
			getSupportFragmentManager().putFragment(save, "PEERS", _peers_fragment);
	}

	@Override
	public void onRestoreInstanceState(Bundle restore){
		if(restore.containsKey("LOGIN"))
			_login_fragment = (LoginFragment) getSupportFragmentManager().getFragment(restore, "LOGIN");
		if(restore.containsKey("TWEETS"))
			_tweets_fragment = (TweetsFragment) getSupportFragmentManager().getFragment(restore, "TWEETS");
		if(restore.containsKey("PEERS"))
			_peers_fragment = (PeersFragment) getSupportFragmentManager().getFragment(restore, "PEERS");

		super.onRestoreInstanceState(restore);
	}
	@Override
	public void onNewUsers(ArrayList<String> users) {
		runOnUiThread(new Runnable(){
			public void run(){
				if(_peers_fragment != null){
					_peers_fragment.refresh();
				}else if(_tweets_fragment != null && !_tweets_fragment.isSmartphone()){
					_tweets_fragment.refreshPeers();
				}
				getSupportActionBar().setDisplayHomeAsUpEnabled(_tweets_fragment != null && _tweets_fragment.isSmartphone());

			}
		});
	}

	public void onClickLogin(String item) {
		if(_tweets_fragment != null)
			_tweets_fragment.onClickLogin(item);
	}
}
